package com.github.lh.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.github.lh.common.BindingResultChecker.extractErrorsReturn;
import static com.github.lh.common.ReturnModel.just;
import static org.springframework.context.i18n.LocaleContextHolder.getLocale;

/**
 * @author <a href="mailto: 393803588@qq.com">刘涵(Hanl)</a>
 * By 2017/12/2
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @Autowired
    MessageSource messageSource;

    /**
     * custom BizException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BizException.class)
    public ReturnModel<?> exceptionHandler(BizException e) {
        return just(e.getCode(), msg(e.getMessageCode(), e.getArgs()));
    }

    /**
     * BindException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public ReturnModel<?> exceptionHandler(BindException e) {
        return just(ReturnCode.BAD_REQUEST, extractErrorsReturn(e));
    }

    /**
     * other Exception
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ReturnModel<?> exceptionHandler(Exception e) {
        return just(ReturnCode.UNKNOWN_ERROR, e.getMessage());
    }


    private String msg(String code, Object... args) {
        return this.messageSource.getMessage(code, args, getLocale());
    }
}
